const cmurl = 'http://124.223.14.236:3001';
const token = localStorage.getItem('token');
const myId = localStorage.getItem('id');

let pageNum = 1;
let totalNum = 0;
let orderBy = 'id';
let sortBy = 'desc';

// 响应拦截器
axios.interceptors.response.use(
  function (response) {
    return response;
  },
  function (error) {
    console.log('请求错误');
    console.dir(error);
    if (
      error.response &&
      error.response.status &&
      error.response.status === 401
    ) {
      if (error.response.data.message === 'jwt expired') {
        alert('token过期了，请重新登录');
      } else {
        alert('请携带token发生请求');
      }
    }
    // 请求错误
    return Promise.reject(error);
  }
);

// 留言列表接口
function getNoteList(call) {
  axios({
    method: 'GET',
    url: cmurl + '/api/notes',
    params: {
      pageSize: 5,
      pageNum,
      order: orderBy,
      sort: sortBy,
    },
  }).then(function (result) {
    call(result);
  });
}

// 留言详情接口
function getNoteDetail(id, call) {
  axios({
    method: 'GET',
    url: cmurl + '/api/notes/' + id,
    params: {},
  }).then(function (result) {
    call(result);
  });
}

// 添加留言接口
function addNote(content) {
  axios({
    method: 'POST',
    url: cmurl + '/api/notes',
    data: {
      content,
    },
    headers: {
      Authorization: token,
    },
  }).then(function (result) {
    if (result.status === 200) {
      pageNum = 1;
      alert('添加留言成功！');
      render();
    } else {
      alert('添加留言失败！');
    }
  });
}

// 删除留言接口
function getNoteDetail(id) {
  axios({
    method: 'DELETE',
    url: cmurl + '/api/notes/' + id,
    headers: {
      Authorization: token,
    },
  }).then(function (result) {
    console.log(result);
    if (result.status === 200) {
      alert('删除成功！');
      render();
    } else {
      alert('删除失败！');
    }
  });
}

// 渲染函数
function render() {
  getNoteList(function (res) {
    totalNum = res.data.data.total;
    const list = res.data.data.list;
    // console.log(list)
    // 渲染留言内容
    document.querySelector('ul.comm-list').innerHTML = list
      .map((item, index) => {
        const { avatar, content, id, sex, time, user_id, username, vip } = item;
        return `
        <li class="comm-item">
          <div class="avatar" style="background-image: url('${cmurl + '/public/avatar/default_empty.png'
          }');"></div>
          <div class="info">
            <p class="name ${vip ? 'vip' : ''}">
              ${username}
              ${vip ? '<img alt="" src="https://gw.alicdn.com/tfs/TB1c5JFbGSs3KVjSZPiXXcsiVXa-48-48.png" />'
            : ''
          }
            </p>
            <p class="time">
              <span>${new Date(+time)
            .toLocaleDateString()
            .replaceAll('/', '-')}</span>
              <span class="del" data-id=${id} style="display:${+myId === +user_id ? '' : 'none'}">删除</span>
            </p>
            <p>
              ${content}
            </p>
          </div>
        </li>
      `;
      })
      .join('');

    // 渲染总数
    document.querySelector('sub').innerHTML = '(' + totalNum + ')';
  });
}
